package com.shenmazong.demo1907amongo.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.demo1907amongo.mapper.ITbUserMapper;
import com.shenmazong.demo1907amongo.pojo.TbBlog;
import com.shenmazong.demo1907amongo.pojo.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2021/12/8 11:44
 */

@Component
@EnableScheduling
@Slf4j
public class MongoTaskWork {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ITbUserMapper iTbUserMapper;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    private Boolean isCreatedEs = false;

    // 全量同步 -> 增量同步

    @Scheduled(fixedRate = 1000*60)
    public void syncTbUser() {
        log.info("task........");
        // select * from tb_user where mongo_flag=0
        List<TbUser> tbUsers = iTbUserMapper.selectList(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getMongoFlag, 0)
        );

        tbUsers.forEach(user -> {
            // 更新mongodb
            user.setMongoFlag(1);
            mongoTemplate.save(user);

            // 更新mysql中的同步字段
            iTbUserMapper.updateById(user);
        });
        log.info("task........ok");
    }
}
